<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="nav-left" @tap="goBack">
        <uni-icons type="arrowleft" size="24" color="#333"></uni-icons>
      </view>
      <view class="nav-center">
        <text class="nav-title">收藏</text>
      </view>
      <view class="nav-right">
        <view class="nav-item" @tap="toggleManageMode">
          <uni-icons type="trash" size="24" color="#333"></uni-icons>
          <text class="nav-text">{{ isManageMode ? '完成' : '管理' }}</text>
        </view>
      </view>
    </view>

    <!-- 标签页 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'all' }" 
        @tap="switchTab('all')"
      >
        <text class="tab-text">全部</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'restaurant' }" 
        @tap="switchTab('restaurant')"
      >
        <text class="tab-text">餐厅</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'dish' }" 
        @tap="switchTab('dish')"
      >
        <text class="tab-text">菜品</text>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input 
          type="text" 
          placeholder="搜索收藏的餐厅" 
          v-model="searchKeyword"
          @confirm="onSearch"
        />
      </view>
      <view class="search-btn" @tap="onSearch">
        <text class="btn-text">搜索</text>
      </view>
    </view>

    <!-- 收藏列表 -->
    <view class="favorites-list">
      <view 
        class="favorite-item" 
        v-for="(item, index) in filteredFavorites" 
        :key="item.id"
      >
        <!-- 选择框（管理模式下显示） -->
        <view class="select-box" v-if="isManageMode">
          <uni-icons 
            :type="selectedItems.includes(index) ? 'checkbox-filled' : 'circle'" 
            :color="selectedItems.includes(index) ? '#00C853' : '#ccc'"
            size="24"
            @tap="toggleSelectItem(index)"
          ></uni-icons>
        </view>

        <!-- 餐厅信息 -->
        <view class="item-content" :class="{ 'manage-mode': isManageMode }">
          <view class="item-image">
            <image 
              :src="item.image || '/static/logo.png'" 
              mode="aspectFill"
            ></image>
          </view>
          
          <view class="item-details">
            <view class="item-name">{{ item.name }}</view>
            
            <view class="item-rating">
              <uni-icons type="star-filled" size="14" color="#FFD700"></uni-icons>
              <text class="rating-text">{{ item.rating }}</text>
              <text class="sales-text">月售{{ item.sales }}单</text>
            </view>
            
            <view class="item-price-info">
              <text class="min-price">¥{{ item.minPrice }}起送</text>
              <text class="delivery-fee">配送费¥{{ item.deliveryFee }}</text>
            </view>
            
            <view class="item-distance">
              <uni-icons type="location-filled" size="14" color="#999"></uni-icons>
              <text class="distance-text">{{ item.distance }}km</text>
            </view>
            
            <view class="item-discounts" v-if="item.discounts && item.discounts.length > 0">
              <view class="discount-tag" v-for="(discount, dIndex) in item.discounts" :key="dIndex">
                {{ discount }}
              </view>
            </view>
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="item-actions" v-if="!isManageMode">
          <button 
            class="action-btn view-btn" 
            @tap="viewRestaurant(item)"
          >
            去看看
          </button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="filteredFavorites.length === 0">
      <uni-icons type="star" size="80" color="#ccc"></uni-icons>
      <text class="empty-text">暂无收藏内容</text>
    </view>

    <!-- 底部操作栏（管理模式下显示） -->
    <view class="bottom-bar" v-if="isManageMode">
      <view class="select-all" @tap="toggleSelectAll">
        <uni-icons 
          :type="isAllSelected ? 'checkbox-filled' : 'circle'" 
          :color="isAllSelected ? '#00C853' : '#ccc'"
          size="24"
        ></uni-icons>
        <text class="select-text">全选</text>
      </view>
      <button 
        class="delete-btn" 
        :disabled="selectedItems.length === 0"
        @tap="deleteSelected"
      >
        删除({{ selectedItems.length }})
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { getUserFavorites, deleteFavorite } from '@/api/auth';

const userStore = useUserStore();

// 数据状态
const activeTab = ref('all');
const searchKeyword = ref('');
const isManageMode = ref(false);
const selectedItems = ref<number[]>([]);
const favoritesData = ref<any[]>([]);

// 加载收藏列表
const loadFavorites = async () => {
  if (!userStore.userInfo?.customerId) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({ title: '加载中...' });
    const data: any = await getUserFavorites(userStore.userInfo.customerId);
    
    // 后端返回的数据格式可能需要转换
    if (data && Array.isArray(data)) {
      favoritesData.value = data.map((item: any) => ({
        id: item.favoriteId || item.id,
        productId: item.productId,
        name: item.productName || item.name || '未知商品',
        image: item.productImage || item.image || '/static/logo.png',
        rating: item.rating || 4.5,
        sales: item.sales || 0,
        minPrice: item.minPrice || 0,
        deliveryFee: item.deliveryFee || 0,
        distance: item.distance || 0,
        discounts: item.discounts || [],
        type: item.type || 'restaurant'
      }));
    } else {
      favoritesData.value = [];
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error);
    // 失败时使用模拟数据
    favoritesData.value = mockFavorites;
  } finally {
    uni.hideLoading();
  }
};

// 模拟收藏数据(作为后备数据)
const mockFavorites = [
  {
    id: 1,
    productId: 1,
    name: '绿光餐厅（科技园店）',
    image: '/static/shangjia01.png',
    rating: 4.5,
    sales: 1230,
    minPrice: 20,
    deliveryFee: 3,
    distance: 1.2,
    discounts: ['满50减15', '新客立减8元'],
    type: 'restaurant'
  },
  {
    id: 2,
    productId: 2,
    name: '和风寿司料理（科创城店）',
    image: '/static/shangjia02.png',
    rating: 4.8,
    sales: 980,
    minPrice: 30,
    deliveryFee: 4,
    distance: 2.5,
    discounts: ['第二杯半价', '新品8折'],
    type: 'restaurant'
  },
  {
    id: 3,
    productId: 3,
    name: '川味小馆',
    image: '/static/shangjia03.png',
    rating: 4.3,
    sales: 2100,
    minPrice: 15,
    deliveryFee: 2,
    distance: 0.8,
    discounts: ['满30减10'],
    type: 'restaurant'
  }
];

// 计算属性：过滤后的收藏列表
const filteredFavorites = computed(() => {
  let result = favoritesData.value.length > 0 ? favoritesData.value : mockFavorites;
  
  // 根据标签页过滤
  if (activeTab.value !== 'all') {
    result = result.filter(item => item.type === activeTab.value);
  }
  
  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    result = result.filter(item => 
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  
  return result;
});

// 计算属性：是否全选
const isAllSelected = computed(() => {
  return selectedItems.value.length > 0 && 
         selectedItems.value.length === filteredFavorites.value.length;
});

// 切换标签页
const switchTab = (tab: string) => {
  activeTab.value = tab;
};

// 搜索
const onSearch = () => {
  // 搜索逻辑已通过computed实现
  console.log('搜索:', searchKeyword.value);
};

// 查看餐厅详情
const viewRestaurant = (item: any) => {
  uni.showToast({
    title: `查看${item.name}`,
    icon: 'none'
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 切换管理模式
const toggleManageMode = () => {
  isManageMode.value = !isManageMode.value;
  if (!isManageMode.value) {
    selectedItems.value = [];
  }
};

// 切换选择单项
const toggleSelectItem = (index: number) => {
  const selectedIndex = selectedItems.value.indexOf(index);
  if (selectedIndex > -1) {
    selectedItems.value.splice(selectedIndex, 1);
  } else {
    selectedItems.value.push(index);
  }
};

// 切换全选
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedItems.value = [];
  } else {
    selectedItems.value = Array.from({ length: filteredFavorites.value.length }, (_, i) => i);
  }
};

// 删除选中的收藏
const deleteSelected = async () => {
  if (selectedItems.value.length === 0) {
    uni.showToast({
      title: '请选择要删除的项',
      icon: 'none'
    });
    return;
  }

  uni.showModal({
    title: '提示',
    content: `确定要删除选中的${selectedItems.value.length}个收藏吗?`,
    success: async (res) => {
      if (res.confirm && userStore.userInfo?.customerId) {
        try {
          // 批量删除
          const promises = selectedItems.value.map(index => {
            const item = filteredFavorites.value[index];
            return deleteFavorite(userStore.userInfo!.customerId, item.productId);
          });
          
          await Promise.all(promises);
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          // 重新加载列表
          selectedItems.value = [];
          isManageMode.value = false;
          loadFavorites();
        } catch (error) {
          console.error('删除收藏失败:', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 页面加载时获取收藏数据
onMounted(() => {
  loadFavorites();
});
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20rpx;
}

/* 导航栏样式 */
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 999;
}

.nav-left, .nav-right {
  display: flex;
  align-items: center;
  width: 120rpx;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-item {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.nav-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

/* 标签页样式 */
.tabs {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15rpx 0;
}

.tab-item.active {
  border-bottom: 4rpx solid #00C853;
}

.tab-text {
  font-size: 30rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #00C853;
  font-weight: bold;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  padding: 0 30rpx 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.search-input {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  padding: 0 20rpx;
}

.search-input input {
  flex: 1;
  padding: 15rpx 20rpx;
  font-size: 28rpx;
}

.search-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #00C853;
  border-radius: 30rpx;
  margin-left: 20rpx;
  padding: 0 30rpx;
}

.btn-text {
  color: #fff;
  font-size: 28rpx;
}

/* 收藏列表样式 */
.favorites-list {
  padding: 0 30rpx;
}

.favorite-item {
  display: flex;
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.select-box {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.item-content {
  flex: 1;
  display: flex;
}

.item-content.manage-mode {
  width: calc(100% - 50rpx);
}

.item-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  overflow: hidden;
  margin-right: 20rpx;
}

.item-image image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.item-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.item-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.rating-text {
  font-size: 24rpx;
  color: #FFD700;
  margin: 0 10rpx;
}

.sales-text {
  font-size: 24rpx;
  color: #999;
}

.item-price-info {
  display: flex;
  margin-bottom: 10rpx;
}

.min-price {
  font-size: 24rpx;
  color: #00C853;
  margin-right: 20rpx;
}

.delivery-fee {
  font-size: 24rpx;
  color: #999;
}

.item-distance {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.distance-text {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.item-discounts {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.discount-tag {
  font-size: 20rpx;
  color: #ff3b30;
  border: 1rpx solid #ff3b30;
  border-radius: 4rpx;
  padding: 4rpx 8rpx;
}

.item-actions {
  display: flex;
  align-items: flex-end;
}

.view-btn {
  background-color: #00C853;
  color: #fff;
  border: none;
  border-radius: 30rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

/* 底部操作栏样式 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.select-all {
  display: flex;
  align-items: center;
}

.select-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.delete-btn {
  background-color: #ff3b30;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  padding: 15rpx 30rpx;
  font-size: 28rpx;
}

.delete-btn[disabled] {
  background-color: #ccc;
}
</style>